package com.hjh.shirodemo.web.config;

import com.hjh.shirodemo.entity.UserBean;
import com.hjh.shirodemo.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private IUserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("权限认证 -->MyShiroRealm.doGetAuthorization()");
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("身份认证：MyShiroRealm.doGetAuthenticationInfo()");
        //获取用户输入的账号
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String usrName = token.getUsername();
        String usrPassword = new String(token.getPassword());
        System.out.println("usrName"+usrName);
        System.out.println("usrPassword"+usrPassword);
        UserBean user =userService.getUser(usrName);
        System.out.println("---->>user="+user);
        if (user == null){
            throw new UnknownAccountException("账号不存在!");
        }else if (!user.getUsrPassword().equals(usrPassword)){
            throw new IncorrectCredentialsException("密码不正确");
        }
        //认证信息
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user,//用户
                user.getUsrPassword(),//密码
                getName()
        );
        return authenticationInfo;
    }

}
